/***
 * @Author: 玄绮 shijiahansi@qq.com
 * @Date: 2024-06-08 09:15:52
 * @LastEditors: 玄绮 shijiahansi@qq.com
 * @LastEditTime: 2024-06-08 09:46:54
 * @FilePath: \server\dep\rdhttp\body\HttpBoundaryBody.cpp
 * @Description:
 * @
 * @Copyright (c) 2024 by 玄绮, All Rights Reserved.
 */
#include "FormItem.h"

#include <boost/algorithm/string.hpp>
#include <filesystem>
#include <fstream>
#include <string/stringsplit.h>
#include <string_view>
#include <tools/tools.h>

namespace fs = std::filesystem;

using namespace boost;
namespace rdhttp {

    FormItem::FormItem(std::string_view data) {
        pares(data);
    }

    FormItem::~FormItem() {
    }

    void FormItem::pares_head(StringView head) {
        auto list = split(head, "\r\n");

        for (auto&& i : list) {
            auto pos   = i.find_first_of(':');
            auto name  = std::string(i.substr(0, pos));
            auto value = std::string(i.substr(pos + 1));
            trim(name);
            trim(value);
            if (name == "Content-Type") {
                m_content_type.pares(value);
            }
            else if (name == "Content-Disposition") {
                m_content_dispotion.pares(value);
            }
        }
    }

    void FormItem::pares(StringView data) {
        if (boost::ends_with(data, "\r\n")) data.remove_suffix(2);
        if (boost::starts_with(data, "\r\n")) {
            m_content = data;
            m_content.remove_prefix(2);
        }
        else {
            auto post = data.find("\r\n\r\n");

            StringView head = data.substr(0, post);

            pares_head(head);

            post += 4;
            m_content = data.substr(post);
        }
    }

    bool FormItem::save_as(fs::path newpath) const {
        if (!fs::exists(newpath.parent_path())) {
            fs::create_directories(newpath.parent_path());
        }

        std::ofstream fout(to_local(newpath.string()), std::ios::binary);
        if (fout.is_open()) {
            fout.write(m_content.data(), m_content.size());
            fout.close();
            return true;
        }
        return false;
    }

    const ContentType& FormItem::content_type() const {
        // TODO: 在此处插入 return 语句
        return m_content_type;
    }

    const ContentDisposition& FormItem::content_dispotion() const {
        // TODO: 在此处插入 return 语句
        return m_content_dispotion;
    }

    FormItem::StringView FormItem::content() const {
        return m_content;
    }

}  // namespace rdhttp
